<template>
  <div class="uploadCardWrap">
    <van-uploader
      v-model="localFileList"
      :preview-size="[270, 160]"
      max-count="1"
      :before-read="beforeRead"
      :after-read="afterRead"
      @oversize="onOversize"
    >
      <template #default v-if="localFileList.length === 0">
        <img :src="imageSrc" alt="" class="uploadImg" />
      </template>
    </van-uploader>
  </div>
</template>
<script lang="ts" setup>
import { uploadOcr } from '@/api'
const props = defineProps({
  type: {
    type: String,
    default: 'IdCard'
  },
  fileList: {
    type: Array,
    default: () => []
  },
  uploadType: {
    type: String,
    default: 'idcardfront'
  }
})

const emit = defineEmits(['update:fileList'])
const localFileList = ref([...props.fileList])
watch(
  () => props.fileList,
  (newVal) => {
    localFileList.value = [...newVal]
  },
  { deep: true }
)

// 动态计算图片路径
const imageSrc = computed(() => {
  try {
    return new URL(`/src/assets/${props.uploadType}.png`, import.meta.url).href
  } catch (error) {
    console.error('图片路径加载失败:', error)
    return '' // 返回默认值或占位图路径
  }
})
const beforeRead = (file) => {
  const limitType = ['image/png', 'image/jpeg'].includes(file.type)
  if (!limitType) {
    showToast('只支持图片文件')
    return false
  }
  const limit = file.size <= 10 * 1024 * 1024
  if (!limit) {
    showToast('图片文件大小不能超过10M')
    return false
  }
  return true
}
const afterRead = async (file) => {
  file.status = 'uploading'
  file.message = '上传中...'
  const formData = new FormData()
  formData.append('file', file.file)
  formData.append('type', props.type)
  try {
    const res = await uploadOcr(formData)
    if (res.data) {
      localFileList.value = [
        {
          url: res.data.url,
          ossId: res.data.ossId
        }
      ]
      file.status = 'done'
      file.message = '上传成功'
      emit('update:fileList', [...localFileList.value])
    }
  } catch (error) {
    file.status = 'failed'
    file.message = '上传失败'
    showToast('上传失败，请稍后再试')
  }
}
const onOversize = (params) => {
  if (params) showToast('图片文件过大，请最大上传10M图片')
}
</script>
<style lang="scss" scoped>
.uploadCardWrap {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  .van-uploader {
    .van-uploader__upload {
    }
  }
  .uploadImg {
    width: 270px;
    height: 160px;
  }
}
</style>
